package com.sly.demoim.handler;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.sly.demoim.constant.ChatConstant;
import com.sly.demoim.controller.ChatWebSocket;
import com.sly.demoim.helper.ChatRedisHelper;
import com.sly.demoim.model.connect.UserConnectInfo;
import com.sly.demoim.model.content.TextContent;
import com.sly.demoim.model.message.ChatMessage;
import com.sly.demoim.model.message.Message;
import com.sly.demoim.result.BaseResult;
import com.sly.demoim.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.websocket.Session;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 文本消息处理器
 *
 * @author SLY
 * @date 2022/7/17
 */
@Slf4j
@Component
public class TextMessageHandler implements MessageHandler {

    @Autowired
    private ChatRedisHelper chatRedisHelper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MessageService messageService;

    @Override
    public void handler(Session session, String messageJsonStr, Map<String, ChatWebSocket> sockets) {
        // 获取消息对象
        ChatMessage<TextContent> message = JSONUtil.toBean(messageJsonStr, new TypeReference<ChatMessage<TextContent>>() {
        }, false);

        // 保存消息信息
        messageService.saveMessage(message);

        // 获取目的对象会话所处服务节点
        UserConnectInfo userConnectInfo = chatRedisHelper.findUserConnectInfo(message.getToUser());
        if (userConnectInfo != null) {
            // 对方在线，直接转发到对应服务器发送消息
            // 请求地址
            String url = "http://" + userConnectInfo.getHost() + ":" + userConnectInfo.getPort() + ChatConstant.CHAT_MSG_REDIRECT_URL;
            URI uri = UriComponentsBuilder.fromHttpUrl(url)
                    .build()
                    .encode(StandardCharsets.UTF_8)
                    .toUri();
            // 请求参数
            RequestEntity<ChatMessage<TextContent>> requestEntity = RequestEntity
                    .post(uri)
                    .header("Accept", MediaType.APPLICATION_JSON.toString())
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .body(message);
            // 发送请求
            ResponseEntity<BaseResult> responseEntity = restTemplate.exchange(requestEntity, BaseResult.class);
            if(responseEntity.getBody() == null || !responseEntity.getBody().isSuccess()){
                log.error("IM消息转发异常，消息:{}，返回结果{}", message, responseEntity.getBody());
            }
        }
    }
}
